import { IObject, Form, OType } from '@cscec/udp-ui';
import React, { useMemo } from 'react';

function getXtype(type: string, item: IObject, render: Function, index: number) {
  if (item.xtype) {
    return {
      xtype: item.xtype,
    };
  }
  if (item.type === 'common-help') {
    return {
      xtype: item.multiple ? 'SingleHelp' : 'MultipleHelp',
    };
  }
  return {
    xtype: (props: any) => render(`body/${index}`, { type, ...item, ...props }),
  };
}

export default ({
  body, id, render, name, data, columnCount, formProps,
}: any) => {
  const innerFields = useMemo(() => body.map((item: any, index: number) => {
    const {
      label, name, readOnly, type, value, ...col
    } = item;
    const commonProps: any = {};
    readOnly && (commonProps.disabled = item.readOnly);
    if (value !== undefined) {
      if (["Switch", 'Checkbox'].includes(col.xtype)) {
        commonProps.defaultValue = value ? 1 : 0;
      } else {
        commonProps.defaultValue = value;
      }
    }
    return {
      langKey: name,
      ...col,
      label,
      name,
      ...commonProps,
      ...getXtype(type, col, render, index),
    };
  }), [body]);

  const cid = formProps?.id || id || 'grid';
  const { oType = OType.Add, stateData = {} } = data || {};
  
  return <Form colspan={columnCount} {...formProps} id={cid} disabled={![OType.Add, OType.Edit].includes(oType)} value={stateData[name]} config={innerFields} />;
};
